﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using App_Code.Helpers;
using PluginDB;

namespace App_Code.SiteParsers
{
    /// <summary>
    /// Summary description for TenNetILParser
    /// </summary>
    public class TenNetILParser : BaseScanner
    {
        private const string BASE_URL = "http://10net.co.il";
        private const string SERIES_URL = "http://10net.co.il/108752/%D7%A1%D7%93%D7%A8%D7%95%D7%AA-%D7%9C%D7%A6%D7%A4%D7%99%D7%99%D7%94-%D7%99%D7%A9%D7%99%D7%A8%D7%94";

        private class SeriesItem
        {
            public string Name { get; set; }
            public string PageUrl { get; set; }
        }

        public TenNetILParser()
        {
            this.Name = "10net.co.il";
        }

        #region Private Methods
        private IEnumerable<SeriesItem> LoadCategories()
        {
            var categories = new List<SeriesItem>
                                 {
                                     new SeriesItem
                                         {
                                             Name = "סרטים ישראלים",
                                             PageUrl =
                                                 "http://www.10net.co.il/108752/%D7%A6%D7%A4%D7%99%D7%99%D7%94-%D7%99%D7%A9%D7%99%D7%A8%D7%94-%D7%91%D7%A1%D7%A8%D7%98%D7%99%D7%9D-%D7%99%D7%A9%D7%A8%D7%90%D7%9C%D7%99%D7%9D"
                                         },
                                     new SeriesItem
                                         {
                                             Name = "קומדיה",
                                             PageUrl =
                                                 "http://www.10net.co.il/108752/%D7%A6%D7%A4%D7%99%D7%99%D7%94-%D7%99%D7%A9%D7%99%D7%A8%D7%94-%D7%91%D7%A1%D7%A8%D7%98%D7%99-%D7%A7%D7%95%D7%9E%D7%93%D7%99%D7%94"
                                         },
                                     new SeriesItem
                                         {
                                             Name = "פעולה",
                                             PageUrl = 
                                                 "http://www.10net.co.il/108752/%D7%A6%D7%A4%D7%99%D7%99%D7%94-%D7%99%D7%A9%D7%99%D7%A8%D7%94-%D7%91%D7%A1%D7%A8%D7%98%D7%99-%D7%90%D7%A7%D7%A9%D7%9F"
                                             
                                         },
                                     new SeriesItem
                                         {
                                             Name = "דרמה",
                                             PageUrl = "http://www.10net.co.il/108752/%D7%A6%D7%A4%D7%99%D7%99%D7%94-%D7%99%D7%A9%D7%99%D7%A8%D7%94-%D7%91%D7%A1%D7%A8%D7%98%D7%99-%D7%93%D7%A8%D7%9E%D7%94"
                                         },
                                     new SeriesItem
                                         {
                                             Name = "אימה",
                                             PageUrl = "http://www.10net.co.il/108752/Horror-Films"
                                         },
                                     new SeriesItem
                                         {
                                             Name = "ילדים",
                                             PageUrl = "http://www.10net.co.il/108752/%D7%A6%D7%A4%D7%99%D7%99%D7%94-%D7%99%D7%A9%D7%99%D7%A8%D7%94-%D7%91%D7%A1%D7%A8%D7%98%D7%99-%D7%99%D7%9C%D7%93%D7%99%D7%9D-%D7%95%D7%A0%D7%95%D7%A2%D7%A8"
                                         },
                                     new SeriesItem
                                         {
                                             Name = "מדע בדיוני",
                                             PageUrl = "http://www.10net.co.il/108752/%D7%9E%D7%93%D7%A2-%D7%91%D7%93%D7%99%D7%95%D7%A0%D7%99-%D7%9C%D7%A6%D7%A4%D7%99%D7%99%D7%94-%D7%99%D7%A9%D7%99%D7%A8%D7%94"
                                         }
                                 };
            return categories;
        }

        private void LoadMovies(string url, string categoryName, string moviesTypeName, int pagesToScan)
        {
            var currentPage = pagesToScan;
            var nextPageLink = GetPageLink(url, currentPage);
            
            do
            {
                var pageContent = Utils.GetPage(nextPageLink, Encoding.UTF8);
                var matches = GetMoviesMatches(pageContent);
                foreach (Match match in matches)
                {
                    var imageLink = WrapUrl(BASE_URL, match.Groups[1].Value);
                    var moviePageLink = WrapUrl(BASE_URL, match.Groups[2].Value);
                    var movieTitle = match.Groups[3].Value;
                    var plot = match.Groups[4].Value;

                    if (IsVideoExists(moviePageLink))
                        continue;

                    var video = FillMovieInfo(movieTitle, moviePageLink, moviesTypeName);
                    video.ImageUrl = imageLink;
                    video.Plot = plot;
                    video.Categories.Add(categoryName);

                    AddVideoToDB(video);
                }

                currentPage--;
                nextPageLink = GetPageLink(url, currentPage);

            } while (currentPage > 0);
        }

        private void LoadSeries(string url, string moviesTypeName, int pagesToScan)
        {
            var currentPage = pagesToScan;
            var nextPageLink = GetPageLink(url, currentPage);

            do
            {
                var pageContent = Utils.GetPage(nextPageLink, Encoding.UTF8);
                var matches = GetMoviesMatches(pageContent);
                foreach (Match match in matches)
                {
                    var imageLink = WrapUrl(BASE_URL, match.Groups[1].Value);
                    var moviePageLink = WrapUrl(BASE_URL, match.Groups[2].Value);
                    var movieTitle = match.Groups[3].Value;
                    var plot = match.Groups[4].Value;

                    if (IsVideoExists(moviePageLink))
                        continue;

                    var video = FillMovieInfo(movieTitle, moviePageLink, moviesTypeName);
                    video.ImageUrl = imageLink;
                    video.Plot = plot;
                    video.Categories.Add(movieTitle);

                    AddVideoToDB(video);
                }

                currentPage--;
                nextPageLink = GetPageLink(url, currentPage);

            } while (currentPage > 0);
        }

        private MatchCollection GetMoviesMatches(string pageContent)
        {
            const string lastViewRegEx = "class=\"tabview visible\">(.+?)<div id=\"lastview\"";
            var lastViewContent = new Regex(lastViewRegEx, RegexOptions.Singleline).Match(pageContent).Value;
            if (string.IsNullOrEmpty(lastViewContent))
                lastViewContent = pageContent;

            const string moviesContainerExpression =
                "<div class=\"movie\">.*?<img.*?src=\"(.+?)\".*?<a href=\"(.+?)\">(.+?)</a>.*?<div class=\"moviedescription\">(.+?)<";
            var exp = new Regex(moviesContainerExpression, RegexOptions.Singleline);
            var matches = exp.Matches(lastViewContent);
            return matches;
        }

        private PluginVideoInfo FillMovieInfo(string movieName, string moviePageLink, string moviesTypeName)
        {
            var pageContent = Utils.GetPage(moviePageLink, Encoding.UTF8);

            var video = new PluginVideoInfo
            {
                VideoName = movieName,
                PluginUrl = moviePageLink,
                SiteName = this.Name,
            };

            #region Get Links
            var links = Utils.GetMovieLinks(pageContent);
            foreach (var link in links)
            {
                video.Links.Add(new PluginVideoInfo.Link
                {
                    LinkURL = link,
                    SourceName = GetLinkSource(link)
                });
            }
            return video;
            #endregion
        }

        private string GetLinkSource(string link)
        {
            const string expression = @"^([a-zA-Z]+:\/\/)?([^\/]+)\/.*?$";
            var match = Regex.Match(link, expression, RegexOptions.Singleline);
            if (match.Success)
            {
                var list = match.Groups[2].Value.Split('.');
                if (list[0] == "www")
                    return list[1];
                return list[0];

            }
            return string.Empty;
        }

        private string GetPageLink(string baseUrl, int curentPage)
        {
            return string.Format("{0}/new/{1}", baseUrl, curentPage);
        }

        private string WrapUrl(string baseUrl, string url)
        {
            return string.Format("{0}{1}", baseUrl, url);
        }

        public int GetLastPageNumber(string baseUrl)
        {
            try
            {
                var pageContent = Utils.GetPage(Utils.LoopDecodeUrl(baseUrl), Encoding.UTF8);

                const string moviePlotExpression = "<div class=\"pageNavigate\".*?class=\"next\">>.*?<a href=\"(.+?)\"";
                var exp = new Regex(moviePlotExpression, RegexOptions.Singleline);
                var match = exp.Match(pageContent);
                if (match.Success)
                {
                    //var urlFormat = string.Format("{0}/new/", baseUrl);
                    var splited = match.Groups[1].Value.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
                    return int.Parse(splited[splited.Length-1]);
                    //var pageNumber = (BASE_URL + match.Groups[1].Value.Trim()).Replace(urlFormat, string.Empty);
                    //return int.Parse(pageNumber);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in GetLastPageLink: {0}", ex.Message);
            }

            return 0;
        }

        public int GetMoviesLastPageNumber(string url)
        {
            return GetLastPageNumber(url);
        }
        #endregion

        #region Implementation of ISiteScanner
        public override void ScanForMovies(int pagesToScan)
        {
            var categories = this.LoadCategories();
            foreach (var category in categories)
            {
                var lastPageNumber = GetMoviesLastPageNumber(category.PageUrl);
                pagesToScan = (pagesToScan == 0 || pagesToScan > lastPageNumber) ? lastPageNumber : pagesToScan;
                this.LoadMovies(category.PageUrl, category.Name, Common.MOVIES_NAME, pagesToScan);
            }
        }

        public override int GetSeriesLastPageNumber()
        {
            return GetLastPageNumber(SERIES_URL);
        }

        public override void ScanForSeries(int pagesToScan)
        {
            var lastPageNumber = GetSeriesLastPageNumber();
            pagesToScan = (pagesToScan == 0 || pagesToScan > lastPageNumber) ? lastPageNumber : pagesToScan;
            this.LoadSeries(SERIES_URL, Common.SERIES_NAME, pagesToScan);
        }
        #endregion
    }
}